

cc.Component.prototype.addAutoReleaseAsset = function (_asset: cc.Asset) {
    let oneTempAuto = this.node.getComponent(AutoReleaseAssets);
    if (!cc.isValid(oneTempAuto)) {
        oneTempAuto = this.node.addComponent(AutoReleaseAssets);
    };
    oneTempAuto.addAutoReleaseAsset(_asset);
};

cc.Component.prototype.addAutoReleaseAssets = function (_assets: cc.Asset[]) {
    let moreTempAuto = this.node.getComponent(AutoReleaseAssets);
    if (!cc.isValid(moreTempAuto)) {
        moreTempAuto = this.node.addComponent(AutoReleaseAssets);
    };
    for (const _assetSelf of _assets) {
        moreTempAuto.addAutoReleaseAsset(_assetSelf);
    };
};

// AutoReleaseAssets
const { ccclass, menu, disallowMultiple } = cc._decorator;
@ccclass
@menu('资源管理/AutoReleaseAssets/自动释放资源')
@disallowMultiple
export default class AutoReleaseAssets extends cc.Component {

    private dynamicsAssets: cc.Asset[] = [];

    // onLoad () {}
    public addAutoReleaseAsset(_asset: cc.Asset) {
        if (cc.isValid(_asset)) {
            _asset.addRef();
            this.dynamicsAssets.push(_asset);
            // console.log("当前动态资源长度==", _asset._name, this.dynamicsAssets.length);

            // cc.log('_asset ===>', _asset._texture._uuid, cc.assetManager.assets._map[_asset._texture._uuid]._ref);
            // let _mapLen = Object.values(cc.assetManager.assets._map).length;
            // cc.log(_mapLen, 'addRef ==>', _asset._name, _asset._ref, _asset._uuid, cc.assetManager.assets._map[_asset._uuid]._ref);
        }
    };

    onDestroy(): void {
        // console.log("继承cc.Component拥有生命周期如果Node销毁就会顺带销毁这里"); 
        for (let index = 0; index < this.dynamicsAssets.length; index++) {
            let _asset: cc.Asset = this.dynamicsAssets[index];
            if (cc.isValid(_asset)) {
                _asset.decRef();
                // cc_Prefab cc_SpriteAtlas cc_SpriteFrame cc_Texture2D cc_TextAsset cc_SkeletonData cc_JsonAsset cc_BitmapFont
                // cc.log('decRef ===>', _asset._texture._uuid, cc.assetManager.assets._map[_asset._texture._uuid]._ref);
                // let _mapLen = Object.values(cc.assetManager.assets._map).length;
                // cc.log(_mapLen, 'decRef ==>', _asset._name, _asset._ref, _asset._uuid);
                // if (_asset._ref == 0) _asset = null;
            }
        }
        this.dynamicsAssets = [];
    };
};